/* eslint-disable*/
// @ts-nocheck
import {
  reactive, Ref, ref,
} from 'vue';
import { message } from 'ant-design-vue';
import { AxiosResponse } from 'axios';
import { GeneralResponse } from '@/types';
export function debounce(fn: any, delay: number) {
  let timeoutID: any = null;
  // eslint-disable-next-line func-names
  return function (...rest: any) {
    clearTimeout(timeoutID);
    const args = rest;
    const that = this;
    timeoutID = setTimeout(() => {
      fn.apply(that, args);
    }, delay);
  };
}

interface AutoRequestOptions {
  loading?: boolean;
  msg?: string;
  onSuccess?: (data: any) => void;
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
type AutoRequestResult<TData, TParams extends Array<any>> = [
  Ref<TData | undefined>,
  (...params: TParams) => Promise<GeneralResponse<TData> | undefined>,
  Ref<boolean>,
];

/**
 * 处理异步函数的调用
 * @param {Function} fun - 异步函数
 * @param {Function|Object|undefined} options - 回调函数、请求配置或undefined
 * @param {Object|undefined} config - 请求配置或undefined
 */
export function useAutoRequest<TData, TParams extends any[] = any[]>(
  fun: (...params: TParams) => Promise<AxiosResponse<GeneralResponse<TData>>>,
  options?: (data: GeneralResponse<TData>) => void | AutoRequestOptions,
  config?: AutoRequestOptions,
): AutoRequestResult<TData, TParams> {
  const requestLoading = ref<boolean>(false);
  const response = ref<TData>();
  const defaultOptions = reactive<AutoRequestOptions>({});

  if (typeof options === 'function') {
    if (typeof config === 'object') {
      Object.assign(defaultOptions, config);
    } else {
      Object.assign(defaultOptions, {
        loading: false,
        msg: '请求失败',
      });
    }
    defaultOptions.onSuccess = options;
  } else if (typeof options === 'object') {
    Object.assign(defaultOptions, options);
  } else {
    Object.assign(defaultOptions, {
      loading: false,
      msg: '请求失败',
    });
  }

  // eslint-disable-next-line consistent-return
  async function run(...params: TParams) {
    try {
      requestLoading.value = true;
      const { data } = await fun(...params);
      if (data.code === 0) {
        response.value = data.data;
        if (defaultOptions.onSuccess) {
          defaultOptions.onSuccess(data.data);
        }
      } else {
        message.error(data.message || defaultOptions.msg);
      }
      return data;
    } catch (error) {
      message.error(defaultOptions.msg);
    } finally {
      requestLoading.value = false;
    }
  }

  return [
    response,
    run,
    requestLoading,
  ];
}
